package com.dm.cloud.controller;

import com.dm.cloud.api.service.IKaptchaService;
import com.dm.cloud.common.R;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Log4j2
@RestController
@RequestMapping("kaptcha")
public class KaptchaController {

    @Autowired
    private IKaptchaService service;

    /**
     * 生成图形验证码
     * @return
     */
    @GetMapping("create")
    public R create(HttpServletRequest request) {
        return  service.create(request);
    }

    /**
     * 校验验证码是否正确
     * @return
     */
    @GetMapping("checkImgCode")
    public R getUserList(@RequestParam("imgCode")String imgCode, HttpServletRequest request){
        return service.checkImgCode(imgCode,request);
    }

    /**
     * 获取json节点内容
     * @param jsonData
     * @param nodeName
     * @return
     * @throws JsonProcessingException
     */
    String getNodeValue(String jsonData,String nodeName) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode node = null ;
        String imgCode = "";

        node = mapper.readTree(jsonData);

        JsonNode leaf = node.get(nodeName);
        if (leaf != null)
            imgCode = leaf.asText();

        return imgCode;
    }

}